package targetToOffer.forthDay;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Godc
 * @description
 */
public class LevelOrder {
}
class Solution {
    /**
     * offer 32-I
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        if(root==null) return new int[]{};
        ArrayList<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode pop = queue.pop();
            res.add(pop.val);
            if(pop.left!=null) queue.add(pop.left);
            if(pop.right!=null) queue.add(pop.right);
        }
        int[] ints = new int[res.size()];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = res.get(i);
        }
        return ints;
    }

    /**
     * offer 32-II
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for(int i = 0;i<size;i++){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
            }
            res.add(list);
        }
        return res;
    }

    /**
     * offer 32-III
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder3(TreeNode root) {
        if(root == null) return new ArrayList<>();
        ArrayList<List<Integer>> res = new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int cnt = 0;
        while(!queue.isEmpty()){
            LinkedList<Integer> list = new LinkedList<>();
            int size = queue.size();
            for (int i = size; i >0 ; i--) {
                TreeNode poll = queue.poll();
                if(res.size() % 2 == 0) list.addLast(poll.val); // 偶数层 -> 队列头部
                else list.addFirst(poll.val); // 奇数层 -> 队列尾部。
                if(poll.left!=null) queue.add(poll.left);
                if(poll.right!=null) queue.add(poll.right);
            }
            res.add(list);
            cnt++;
        }
        return res;
    }
}
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
}